import React, { PropTypes } from 'react'
import ShortId from 'shortid'
import { is, fromJS } from 'immutable'

class VideoItem extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      videoId:ShortId.generate()
    }
  }

  render() {
    let style = {
      width: this.props.width,
      height: this.props.height,
    }
    let ck = this.props.className || ''
    return (
      <div className={ck} id={this.state.videoId} style={style} />
    )
  }

  componentDidMount() {
    let { videoUrl } = this.props
    if (videoUrl.endsWith('.mp4')) {
      // 把初期化放到线程上去做
      setTimeout(this.loadVideo(this.state.videoId, this.props), 0)
    }
  }

  loadVideo(videoId, props) {
    let { coverImgUrl, videoUrl, aspectRatio, autoPlay, width, height } = props

    let flashVars = {}
    // 参考http://www.ckplayer.com/tool/help/29.htm
    // 视频播放地址
    flashVars.f = videoUrl
    // 封面地址
    flashVars.i = `${coverImgUrl}@${width}w_${height}h_90q`
    // 播放结束的动作 调用js函数(function playerstop(){})并且退出全屏
    flashVars.e = 6
    // 是否支持拖动 视频是否支持播放未下载的内容 1:按关键帧进行拖动
    flashVars.h = 1
    // 视频宽高比例
    if (aspectRatio) {
      flashVars.wh = aspectRatio
    }
    // 是否自动播放
    if (autoPlay) {
      flashVars.p = 1
    }
    // 视频调用配置方式 0:调用ckplayer.js
    flashVars.c = 0

    let params = { bgcolor:'#FFF', allowFullScreen:true, allowScriptAccess:'always', wmode:'transparent' }
    let h5Video = [`${videoUrl}->video/mp4`]

    CKobject.embed('/third/ckplayer/ckplayer.swf', videoId, videoId, '100%', '100%', true, flashVars, h5Video, params);
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state),fromJS(nextState))
  }
}

/*
 coverImgUrl   : 封面图片地址
 videoUrl      : 视频地址
 aspectRatio   : 视频的宽:高比例
 width         : 视频容器的宽度
 height        : 视频容器的高度
 * */
VideoItem.propTypes = {
  coverImgUrl   : PropTypes.string.isRequired,
  videoUrl      : PropTypes.string.isRequired,
  aspectRatio   : PropTypes.string,
  width         : PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  height        : PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  className     : PropTypes.string,
  autoPlay      : PropTypes.bool,
}

// <VideoItem
//   coverImgUrl='http://img2.jsbn.com/venus/canmeramanHosterPro/20160321/1458535211448078720150929170217934776_1200x800.jpg@300w_200h_95q'
//   videoUrl='http://img.ksbbs.com/asset/Mon_1605/0ec8cc80112a2d6.mp4'
//   width='600'
//   height='400'
//   aspectRatio='3:2'
//   autoPlay
// />

// class ImageItem extends React.Component {
//
// }

export default VideoItem
